package com.yehui.jdk.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * InheritableThreadLocal 只在创建一个 thread 的时候管用，在线程池复用线程的情况下，不管用，需要手动去操作
 *
 * InheritableThreadLocal 就是在创建 thread 的时候，copy 一份 parent 的 threadLocal
 * @author 业徽
 * @date 2021/7/8
 */
public class InheritableThreadLocalDemo {

    public static void main(String[] args) throws InterruptedException {
        final ThreadLocal<String> inheritableThreadLocalName = new InheritableThreadLocal<>();
        inheritableThreadLocalName.set(inheritableThreadLocalName.getClass().getName());

        final ThreadLocal<String> threadLocalName = new ThreadLocal<>();
        threadLocalName.set(threadLocalName.getClass().getName());

        final CountDownLatch countDownLatch = new CountDownLatch(1);
        final ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService.execute(() -> {
            System.out.println("threadLocalName: " + threadLocalName.get());
            System.out.println("inheritableThreadLocalName: " + inheritableThreadLocalName.get());
            countDownLatch.countDown();
        });

        inheritableThreadLocalName.set(inheritableThreadLocalName.getClass().getName() + "#1");

        executorService.execute(() -> {
            System.out.println("threadLocalName: " + threadLocalName.get());
            System.out.println("inheritableThreadLocalName: " + inheritableThreadLocalName.get());
            countDownLatch.countDown();
        });

        countDownLatch.await();
    }

}
